package com.gxy.learn.thread.example;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.LockSupport;

/**
 * @description: LockSupport
 *
 *
 * LockSupport.unpark 可以比LockSupport.park 先调用
 * @author: gaoxueyong
 * @Date: 2022/11/10 16:26
 */
@Slf4j
public class LockSupportTest {
    static Thread a;
    static Thread b;
    public static void main(String[] args) {
//        test1();
//        test2();
        lockSupportA1B2C3();
    }

    public static void test1() {
        Thread thread = new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                if (i == 5) {
//                    阻塞
                    LockSupport.park();
                }
                System.out.println(i);
            }
        });
        thread.start();
        try {
            TimeUnit.SECONDS.sleep(8);
        } catch (Exception e) {
            e.printStackTrace();
        }
        LockSupport.unpark(thread);
    }
    public static void test2() {
        Thread thread = new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                if (i == 5) {
//                    阻塞
                    LockSupport.park();
                }
                System.out.println(i);
            }
        });
        LockSupport.unpark(thread);
        thread.start();
    }

    public static void lockSupportA1B2C3() {
        char[] a1 = "12345".toCharArray();
        char[] a2 = "abcde".toCharArray();
        a = new Thread(() -> {
            for (char c : a1) {
                log.info("{}", c);
                LockSupport.unpark(b);
                LockSupport.park();
            }

        }, "a1");
        b = new Thread(() -> {
            for (char c : a2) {
                log.info("{}", c);
                LockSupport.park();
                LockSupport.unpark(a);
            }
        }, "a2");
        a.start();
        b.start();

    }
}
